﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using OSGeo.MapGuide;
using System.Collections.Specialized;

namespace NegevGas
{
    /// <summary>
    /// Summary description for srv
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class srv : System.Web.Services.WebService
    {

        private MgSiteConnection conn;
        private MgFeatureService featureService;
        private MgResourceService resourceService;
        private MgMap map;
        private MgLayer layer;

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string selectStreetPoints(string City ,string street, string KeyLayer1, string SearchFld1, string KeySession, string KeyMapName, string KeyACProperty)
        {
            string returnobg = string.Empty;
            returnobg = SetSelect(KeySession, KeyMapName, KeyLayer1, " STREET LIKE '" + street + "'  AND CITYNAME LIKE '" + City + "' ", KeyACProperty);
            return returnobg;
        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

        public StreetListSelected GetStreetListByCity(string City, string KeyLayer1, string SearchFld1, string KeySession, string KeyMapName, string KeyACProperty)
        {
            StreetListSelected returnobg = new StreetListSelected();
            List<Cascadingkeyval> returnlist = new List<Cascadingkeyval>();


            string selectedxml = string.Empty;
            foreach (var item in GetAllCompletionList(" NOT STREET NULL  AND CITYNAME LIKE '" + City + "'  ", KeyLayer1,SearchFld1, KeySession, KeyMapName ).ToList())
            {
                Cascadingkeyval streetitem = new Cascadingkeyval();
                streetitem.key = item;
                streetitem.val = item;
                returnlist.Add(streetitem);
            }
          
            returnobg.streetlist = returnlist;
            
            return returnobg;
            //JavaScriptSerializer serializer = new JavaScriptSerializer();
            //return serializer.Serialize(empData);
        }

        private string  SetSelect(string KeySession, string KeyMapName, string KeyLayer1, string Filter ,string KeyACProperty)
        {

           MgMap map = GetMapByName(KeyMapName, KeySession);
           MgLayer layer = GetLayerToSearch(KeySession, KeyMapName, KeyLayer1);

            string mainSelection = GetMainFeatureSelection(KeyLayer1, Filter, featureService,map);
           
            string xmlmulty =GetXmlMultiselectFromFeature(Filter, map, layer, ref featureService);

            return SetSelectedMultiValuesOnMap(xmlmulty, Filter, layer, ref featureService);

        }
        public void InitializeWebTier()
        {
            string s_basePath;
            // Initialize web tier with the site configuration file.  The config
            // file should be in the same directory as this script.
            //  MapGuideApi.MgInitializeWebTier(HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"] + "../mapserver2012/webconfig.ini");
            s_basePath = HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"];
            MapGuideApi.MgInitializeWebTier(s_basePath + "webconfig.ini");
            //MapGuideApi.MgInitializeWebTier(@"C:\Program Files\Autodesk\Autodesk Infrastructure Web Server Extension 2012\www\webconfig.ini");
        }
        public  MgMap GetMapByName(string MapName, string sessionId)
        {

            InitializeWebTier();
            MgSiteConnection conn = new MgSiteConnection();
            conn.Open(new MgUserInformation(sessionId));
            MgResourceService resourceService = conn.CreateService(MgServiceType.ResourceService) as MgResourceService;
            MgFeatureService featureService = conn.CreateService(MgServiceType.FeatureService) as MgFeatureService;
            MgMap map = new MgMap();
            map.Open(resourceService, MapName);

            return map;
        }
        private MgLayer GetLayerToSearch(string _sessionid, string _mapName, string _layer)
        {
            MgLayer return_layer;
            try
            {
                InitializeWebTier();
                 conn = new MgSiteConnection();
                conn.Open(new MgUserInformation(_sessionid));
                 resourceService = conn.CreateService(MgServiceType.ResourceService) as MgResourceService;
                 featureService = conn.CreateService(MgServiceType.FeatureService) as MgFeatureService;
                MgMap map = new MgMap();
                map.Open(resourceService, _mapName);
                return_layer = map.GetLayers().GetItem(_layer) as MgLayer;
                if (return_layer == null)
                {
                    throw  new Exception("שכבה לא קיימת.");
                }

                StringCollection FilterSelected = new StringCollection();
                return return_layer;
            }
            catch (Exception erroExcp)
            {

                throw;
            }

        }

        private string GetXmlMultiselectFromFeature(string Filter, MgMap _map, MgLayer _layer, ref MgFeatureService _featureServ)
        {
            MgResourceIdentifier featureResId = new MgResourceIdentifier(_layer.GetFeatureSourceId());
            String className = _layer.GetFeatureClassName();
            String layerId2 = _layer.GetObjectId();
            MgFeatureQueryOptions layerQuery = new MgFeatureQueryOptions();
            layerQuery.SetFilter(Filter);
            MgFeatureReader featureReader = _featureServ.SelectFeatures(featureResId, className, layerQuery);

            MgSelection selection = new MgSelection(_map);

            selection.AddFeatures(_layer, featureReader, 0);

            return selection.ToXml();
        }
        private string SetSelectedMultiValuesOnMap(string XmlSelected, string filterq, MgLayer _layer, ref MgFeatureService _featureServ)
        {
            MgFeatureQueryOptions opt = new MgFeatureQueryOptions();
            opt.SetFilter(filterq);

            MgFeatureReader reader = _featureServ.SelectFeatures(
                                               new MgResourceIdentifier(_layer.FeatureSourceId),
                                               _layer.FeatureClassName,
                                               opt
                                            );




            return XmlSelected;

         
        }

        public string[] GetAllCompletionList(string filtertoseach, string LayertoSearch, string Propertytosearch, string sessionIdstr, string MapName)
        {




            List<string> results = new List<string>();
            try
            {
                MgSiteConnection conn = new MgSiteConnection();
                conn.Open(new MgUserInformation(sessionIdstr));

                MgResourceService resourceService = conn.CreateService(MgServiceType.ResourceService) as MgResourceService;
                MgFeatureService featureService = conn.CreateService(MgServiceType.FeatureService) as MgFeatureService;

                MgMap map = new MgMap();
                map.Open(resourceService, MapName);
                MgLayer layer = (MgLayer)map.GetLayers().GetItem(LayertoSearch);
                MgFeatureQueryOptions query = new MgFeatureQueryOptions();
                //SelectAggregate MgFeatureQueryOptions SetFilter
                query.SetFilter(filtertoseach);

                
                MgFeatureReader reader = featureService.SelectFeatures(new MgResourceIdentifier(layer.GetFeatureSourceId()), layer.GetFeatureClassName(), query);
                while (reader.ReadNext())
                {
                    // string val = GetPropertyValue(reader, property);
                    string val = reader.GetString(Propertytosearch);

                   
                    if (!results.Contains(val))
                    results.Add(val);
                    //if (val.StartsWith(prefixText) && !results.Contains(val)) results.Add(val);
                    //if (results.Count >= count) break;
                }
                reader.Close();
                reader.Dispose();
            }
            catch (Exception e)
            {
                results.Add(e.Message);
            }
            results.OrderBy(k => k);
            return results.ToArray();
        }

        private string GetMainFeatureSelection(string layerName, string filter, MgFeatureService _featureService ,MgMap map)
        {
            string result = String.Empty;

            if (String.IsNullOrEmpty(layerName) || String.IsNullOrEmpty(filter))
                return result;

            MgLayer mLayer = map.GetLayers().GetItem(layerName) as MgLayer;
            MgFeatureQueryOptions opt = new MgFeatureQueryOptions();
            opt.SetFilter(filter);

            MgFeatureReader reader = _featureService.SelectFeatures(new MgResourceIdentifier(mLayer.FeatureSourceId), mLayer.FeatureClassName, opt);
            MgSelection sel = new MgSelection();
            sel.AddFeatures(mLayer, reader, 20);
            result = sel.ToXml();
            reader.Close();
            reader.Dispose();

            return result;
        }
    }
     

   

    [Serializable]
    [System.Web.Script.Services.ScriptService]
    public class Cascadingkeyval
    {
       
       public  string key {get;set;}
       public  string val { get; set; }
    }
    [Serializable]
    [System.Web.Script.Services.ScriptService]
    public class StreetListSelected
    { 
    
         public  List<Cascadingkeyval> streetlist {get;set;}
         
    
    }
}
